package com.hjf.ditubiaozhu.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by hejianfeng on 17/3/22.
 */

public class SpUtils {

    /**
     * 保存在手机里面的文件名
     */
    private static final String FILE_NAME = "share_date";
    public static final String HOUSE_INFO = "houseInfo";
    public static final String ESTATE_INFO = "estateInfo";
    public static final String SERIAL_INFO = "serialnfo";

    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     *
     * @param context
     * @param key
     */
    public static <T> void setParam(Context context, String key, T t) {

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if (t instanceof String) {
            editor.putString(key, (String) t) ;
        } else if (t instanceof Integer) {
            editor.putInt(key, (Integer) t);
        } else if (t instanceof Boolean) {
            editor.putBoolean(key, (Boolean) t);
        } else if (t instanceof Long) {
            editor.putLong(key, (Long) t);
        } else if (t instanceof Float) {
            editor.putFloat(key, (Float) t);
        }
        editor.commit();

    }


    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     */
    public static <T> T getParam(Context context, String key, T t) {

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        if (t instanceof String) {
            String str = sp.getString(key, (String) t);
            t = (T) str;
        } else if (t instanceof Integer) {
            Integer in = sp.getInt(key, (Integer) t);
            t = (T) in;
        } else if (t instanceof Long) {
            Long lon = sp.getLong(key, (Long) t);
            t = (T) lon;
        } else if (t instanceof Float) {
            Float fl = sp.getFloat(key, (Float) t);
            t = (T) fl;
        } else if (t instanceof Boolean) {
            Boolean bl = sp.getBoolean(key, (Boolean) t);
            t = (T) bl;
        }
        return t;
    }
}
